/*
 * @Author: yangrongxin
 * @Date: 2021-08-16 17:41:06
 * @LastEditors: guoju
 * @LastEditTime: 2022-01-07 11:29:48
 */
import { useState, useEffect, useRef, useReducer } from 'react';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import { View, Text, Switch, Button } from '@tarojs/components';
import { AtIcon } from 'taro-ui';
import ScrollContent from '@/components/ScrollContent';
import { TEST_STATUS } from '@/pages/My/compoents/MyAssessment/dataDictionary';
import { REMIND_STATUS } from '@/pages/Team/components/TeamItem';
import { getConfirmInfoFlag } from '@/pages/AssessmentDetail/service';
import { UserDataComfirm } from '@/pages/AssessmentDetail/components/index';
import dayjs from 'dayjs';
import { getUserList, getRemind, getTeamEvaluationDetail } from '../../service';
import styles from './index.module.less';

function reducer(state, action) {
  if (action.type === 'update') {
    return {
      ...state,
      ...action.payload,
    };
  }
}

const EvalutaionTableItem = (props: any) => {
  const {
    name,
    status,
    isCondition,
    measureTableId,
    measureTableRecordId,
    evaluationId,
    evaluationType,
    ableEvaluation, // 判断当前列表是不是已过期 1 是有效 2 是无效
    memberView, // 判断当前用户能不能查看报告 1 是可以 0 是不行
    updateSetUserData, // 更新展示当前用户弹窗的方法
  } = props;

  const toTeamTestReport = () => {
    Taro.navigateTo({
      url: `/pages/TestReport/index?measureTableRecordId=${measureTableRecordId}`,
    });
  };

  const toTeamTest = () => {
    getConfirmInfoFlag().then((isFirstLogin: any) => {
      console.log('isFirstLogin', isFirstLogin);
      // 1 已经确认过 2 未确认过
      if (isFirstLogin?.confirmInfoFlag === 1) {
        updateSetUserData({
          isShowUserData: false,
        });
        Taro.navigateTo({
          url: `/EvaluationModule/pages/CheckboxAnwser/index?measureTableId=${measureTableId}&title=${name}&measureTableRecordId=${measureTableRecordId}&evaluationId=${evaluationId}&evaluationType=${evaluationType}`,
        });
      }
      // 当前未确认过 展示弹窗
      if (isFirstLogin?.confirmInfoFlag === 2) {
        updateSetUserData({
          isShowUserData: true,
          measureTableId,
          name,
          measureTableRecordId,
          evaluationId,
          evaluationType,
        });
      }
    });
  };

  /* 获取按钮的描述 */
  const getBtnContent = () => {
    if (ableEvaluation === 2 && status !== TEST_STATUS.FINISH) {
      // 对应的是测评中
      return <Button className={styles.finish}>已过期</Button>;
    }
    if (status === TEST_STATUS.WAITTEST) {
      return (
        <Button className={styles.toTest} onClick={toTeamTest}>
          去测评
        </Button>
      );
    }
    if (status === TEST_STATUS.FINISH && memberView === 1) {
      return (
        <Button className={styles.viewReport} onClick={toTeamTestReport}>
          查看报告
        </Button>
      );
    }
    // 当前没有查看权限 默认展示已完成
    if (status === TEST_STATUS.FINISH && memberView !== 1) {
      return <Button className={styles.finish}>已完成</Button>;
    }
  };

  /* 获取文本的描述 */
  const getTextDesc = () => {
    if (ableEvaluation === 2 && status !== TEST_STATUS.FINISH) {
      return <Text>已过期</Text>;
    }
    if (status === TEST_STATUS.FINISH) {
      return <Text>已完成</Text>;
    }
    if (status === TEST_STATUS.WAITPAY || status === TEST_STATUS.WAITTEST) {
      return <Text className={styles.unFinishNotice}>未完成</Text>;
    }
  };

  return (
    <View className={styles.evalutaionTableItem}>
      {/* 左侧标题的内容 */}
      <View>
        <Text>{name}</Text>
      </View>
      {/* 右侧操作区域的内容 */}
      {isCondition === 'true' ? getTextDesc() : getBtnContent()}
    </View>
  );
};

const EvalutaionTable = () => {
  const {
    params: {
      // true当前是测评情况表 false是综合测评
      isCondition, // 判断当前是综合测评还是测评情况表
      evaluationId, // 团队测评的id用于获取测评的数据
      status: propsStatus, // 当前团队测评对应的测评tab
    },
  } = useRouter();

  const [teamTestData, setTeamTestData] = useState<any>({
    teamId: '',
    name: '',
    teamNums: 0,
    successNums: 0,
    ableEvaluation: 1, // 1 有效 2 无效
    memberView: 1,
  });
  const [hideFinish, setHideFinish] = useState<boolean>(false);
  const [canNotice, setCanNotice] = useState<boolean>(false); // 设置当前能不能点击催测评按钮
  // 存储当前消息确认的数据 展示对应的跳转路径以及跳转参试的存储
  const [state, dispatch] = useReducer(reducer, {
    isShowUserData: false, // 控制当前弹窗是不是展示
    measureTableId: '',
    measureTableRecordId: '',
    evaluationType: '',
  });

  const { isShowUserData, measureTableId, evaluationType, measureTableRecordId } = state;

  const updateSetUserData = (payload: any) => {
    dispatch({
      type: 'update',
      payload,
    });
  };

  const scrollContentRef = useRef<any>();

  useEffect(() => {
    Taro.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#f7f6ff',
    });
  }, []);

  useDidShow(() => {
    scrollContentRef?.current?.reload({
      evaluationId,
      hideSuccess: hideFinish ? 1 : 2,
      status: Number(propsStatus) === 2 ? 0 : propsStatus,
    });
  });

  /* 控制当前是不是已完成 */
  const onSwitchChange = (event) => {
    const {
      detail: { value },
    } = event;
    setHideFinish(value);
    scrollContentRef?.current?.reload({
      evaluationId,
      hideSuccess: value ? 1 : 2,
      status: value ? 2 : 0,
    });
  };

  const onMakeAssessment = () => {
    getRemind({ evaluationId }).then((res: any) => {
      if (res) {
        Taro.showToast({
          title: '催测评成功！',
          icon: 'none',
        });
        setCanNotice(false);
      }
    });
  };

  // 获取数据的方法
  const onDataFetch = (scrollContentRes) => {
    const { remindStatus } = scrollContentRes;
    setCanNotice(remindStatus === REMIND_STATUS.ENABLE);
  };

  const { endTime, name, successNums, teamNums, ableEvaluation, memberView } = teamTestData;

  let requestFn: any = getTeamEvaluationDetail;
  if (isCondition === 'true') requestFn = getUserList;

  return (
    <View className={styles.container}>
      {/* 测评情况的头部 */}
      {isCondition === 'true' ? (
        <View className={styles.header}>
          <View className={styles.withBtn}>
            <View>
              <Text>{name}</Text>
              <View>
                <Text>已测评</Text>
                <Text>{successNums}</Text>
                <Text>/</Text>
                <Text>{teamNums}</Text>
              </View>
            </View>
            {canNotice && (
              <View onClick={onMakeAssessment}>
                <AtIcon value="bell" size="15" />
                <Text>催测评</Text>
              </View>
            )}
          </View>
          <View className={styles.switchTable}>
            <Text>姓名</Text>
            <View>
              <Text>隐藏已完成</Text>
              <Switch checked={hideFinish} color="#866dd8" onChange={onSwitchChange} />
            </View>
          </View>
        </View>
      ) : (
        <View className={styles.header}>
          <View className={styles.noBtn}>
            <Text>{name}</Text>
            <Text>截止日期：{dayjs(endTime).format('YYYY年MM月DD日')}</Text>
          </View>
          <View className={styles.switchTable}>
            <Text>测评内容</Text>
            {TEST_STATUS.WAITTEST === Number(propsStatus) && (
              <View>
                <Text>隐藏已完成</Text>
                <Switch checked={hideFinish} color="#866dd8" onChange={onSwitchChange} />
              </View>
            )}
          </View>
        </View>
      )}
      {/* TODO: 测评情况的列表 */}
      <ScrollContent
        ref={scrollContentRef}
        // onLoadWhenShow
        extendScrollContent={styles.wapperContent}
        request={async (data: any) => {
          const {
            teamId: resTeamID,
            name: resName,
            teamNums: resTeamNums,
            successNums: resSuccessNums,
            endTime: resEndTime,
            ableEvaluation: resAbleEvaluation,
            // 0 禁止 1 允许 控制当前能不能查看报告
            memberView: resMemberView,
            ...otherProps
          } = await requestFn(data);
          if (isCondition === 'true') {
            if (!name) {
              setTeamTestData({
                teamId: resTeamID,
                name: resName,
                teamNums: resTeamNums,
                successNums: resSuccessNums,
                ableEvaluation: resAbleEvaluation,
              });
            }
            return otherProps;
          }
          if (isCondition !== 'true') {
            setTeamTestData({
              name: resName,
              endTime: resEndTime,
              ableEvaluation: resAbleEvaluation,
              memberView: resMemberView,
            });
            const { measureTableList } = otherProps;
            return {
              content: measureTableList,
              total: measureTableList.length,
            };
          }
        }}
        params={{
          evaluationId,
          // 用于团队的测评情况表中的请求
          hideSuccess: hideFinish ? 1 : 2,
          // 用于我的测评中的团队测评的请求
          status: Number(propsStatus) === 2 ? 0 : propsStatus,
        }}
        itemProps={{
          isCondition,
          ableEvaluation,
          memberView,
          updateSetUserData,
        }}
        onDataFetch={onDataFetch}
        ScrollItem={EvalutaionTableItem}
      />
      {/* 展示补充信息的弹窗 */}
      <UserDataComfirm
        isOpened={isShowUserData}
        toPayFn={() => {
          Taro.navigateTo({
            url: `/EvaluationModule/pages/CheckboxAnwser/index?measureTableId=${measureTableId}&title=${name}&measureTableRecordId=${measureTableRecordId}&evaluationId=${evaluationId}&evaluationType=${evaluationType}`,
          });
        }}
        onClose={() => updateSetUserData({ isShowUserData: false })}
      />
    </View>
  );
};

export default EvalutaionTable;
